// 首页JavaScript逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const elements = {
        homeTab: document.getElementById('home-tab'),
        settingsTab: document.getElementById('settings-tab'),
        monthlySalary: document.getElementById('monthlySalary'),
        todaySalary: document.getElementById('todaySalary'),
        monthlyEarned: document.getElementById('monthlyEarned'),
        payDate: document.getElementById('payDate'),
        yearlySalary: document.getElementById('yearlySalary'),
        bonusProgress: document.getElementById('bonusProgress'),
        refreshBtn: document.getElementById('refreshBtn'),
        shareBtn: document.getElementById('shareBtn'),
        loadingOverlay: document.getElementById('loadingOverlay')
    };

    // 验证元素是否存在
    if (!elements.monthlySalary || !elements.todaySalary || !elements.monthlyEarned || 
        !elements.payDate || !elements.yearlySalary || !elements.bonusProgress) {
        console.error('Required elements not found');
        return;
    }

    // Tab切换功能
    if (elements.settingsTab) {
        elements.settingsTab.addEventListener('click', function() {
            window.location.href = '../settings/index.html';
        });
    }

    // 显示/隐藏加载动画
    function toggleLoading(show) {
        if (elements.loadingOverlay) {
            elements.loadingOverlay.style.display = show ? 'flex' : 'none';
        }
    }

    // 更新工资显示
    function updateSalaryDisplay() {
        try {
            const salaryInfo = CowHorseClock.calculateSalaryInfo();
            
            // 更新DOM
            elements.monthlySalary.textContent = CowHorseClock.formatCurrency(salaryInfo.monthlySalary);
            elements.todaySalary.textContent = CowHorseClock.formatCurrency(salaryInfo.todaySalary);
            elements.monthlyEarned.textContent = CowHorseClock.formatCurrency(salaryInfo.monthlySalaryEarned);
            elements.payDate.textContent = salaryInfo.payDate;
            elements.yearlySalary.textContent = CowHorseClock.formatCurrency(salaryInfo.yearlySalary);
            
            // 计算年终奖进度
            const today = new Date();
            const yearStart = new Date(today.getFullYear(), 0, 1);
            const yearEnd = new Date(today.getFullYear(), 11, 31);
            const settings = CowHorseClock.getStoredSettings();
            const yearProgress = CowHorseClock.calculateWorkdays(yearStart, today, settings.includeWeekends);
            const yearTotalWorkdays = CowHorseClock.calculateWorkdays(yearStart, yearEnd, settings.includeWeekends);
            const bonusProgress = yearTotalWorkdays > 0 ? (yearProgress / yearTotalWorkdays) * salaryInfo.yearlyBonus : 0;
            elements.bonusProgress.textContent = CowHorseClock.formatCurrency(bonusProgress);
            
            // 添加动画效果
            animateSalaryCards();
        } catch (error) {
            console.error('Error updating salary display:', error);
            CowHorseClock.showToast('更新失败，请重试', 'error');
        }
    }

    // 工资卡片动画效果
    function animateSalaryCards() {
        const cards = document.querySelectorAll('.salary-card');
        cards.forEach((card, index) => {
            card.style.transform = 'scale(1.02)';
            setTimeout(() => {
                card.style.transform = 'scale(1)';
            }, 200 + index * 50);
        });
    }

    // 刷新功能
    function refreshData() {
        toggleLoading(true);
        
        // 模拟加载延迟
        setTimeout(() => {
            updateSalaryDisplay();
            toggleLoading(false);
            CowHorseClock.showToast('数据已刷新');
        }, 800);
    }

    // 分享功能
    function shareData() {
        const salaryInfo = CowHorseClock.calculateSalaryInfo();
        const shareText = `🐂🐎时钟工资信息\n\n` +
                        `月薪: ${CowHorseClock.formatCurrency(salaryInfo.monthlySalary)}\n` +
                        `今日已得: ${CowHorseClock.formatCurrency(salaryInfo.todaySalary)}\n` +
                        `本月已得: ${CowHorseClock.formatCurrency(salaryInfo.monthlySalaryEarned)}\n` +
                        `年薪: ${CowHorseClock.formatCurrency(salaryInfo.yearlySalary)}\n` +
                        `发薪日: 每月${salaryInfo.payDate}号\n` +
                        `年终奖: ${CowHorseClock.formatCurrency(salaryInfo.yearlyBonus)}\n\n` +
                        `精准计算你的每一份努力 💪`;

        // 检查是否支持Web Share API
        if (navigator.share) {
            navigator.share({
                title: '牛马时钟 - 工资信息',
                text: shareText
            }).catch(err => {
                console.log('分享失败:', err);
                copyToClipboard(shareText);
            });
        } else {
            copyToClipboard(shareText);
        }
    }

    // 复制到剪贴板
    function copyToClipboard(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                CowHorseClock.showToast('工资信息已复制到剪贴板');
            }).catch(err => {
                console.error('复制失败:', err);
                fallbackCopyTextToClipboard(text);
            });
        } else {
            fallbackCopyTextToClipboard(text);
        }
    }

    // 备用复制方法
    function fallbackCopyTextToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            CowHorseClock.showToast('工资信息已复制到剪贴板');
        } catch (err) {
            console.error('复制失败:', err);
            CowHorseClock.showToast('复制失败，请手动复制', 'error');
        }
        
        document.body.removeChild(textArea);
    }

    // 事件监听器
    if (elements.refreshBtn) {
        elements.refreshBtn.addEventListener('click', refreshData);
    }
    
    if (elements.shareBtn) {
        elements.shareBtn.addEventListener('click', shareData);
    }

    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl+R 或 Cmd+R 刷新
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            refreshData();
        }
        
        // Ctrl+S 或 Cmd+S 分享
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            shareData();
        }
    });

    // 初始化页面
    updateSalaryDisplay();
    
    // 每分钟更新一次显示
    setInterval(updateSalaryDisplay, 60000);
    
    // 监听storage变化，实现多标签页同步
    window.addEventListener('storage', function(e) {
        if (e.key === 'cowHorseClockSettings') {
            updateSalaryDisplay();
        }
    });

    // 检查是否首次使用
    const settings = CowHorseClock.getStoredSettings();
    if (settings.monthlySalary === 0) {
        setTimeout(() => {
            CowHorseClock.showToast('请先到设置页面配置工资信息', 'warning');
        }, 1000);
    }
});